package com.wbao.dianniu.manager;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;

import android.content.Context;
import android.telephony.TelephonyManager;

import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.db.DbManager;
import com.wbao.dianniu.http.Batch;
import com.wbao.dianniu.http.Command;
import com.wbao.dianniu.http.HttpUtil;
import com.wbao.dianniu.http.HttpUtil.MyResponse;
import com.wbao.dianniu.listener.ILogin;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Action;
import com.wbao.dianniu.utils.JsonUtil;

public class LoginManager implements ILogin {

	private ILoginListener mListener = null;
	private Context mContext;
	private String mobile=null;
	public LoginManager(Context context) {
		mContext = context;
	}

	@Override
	public boolean addLoginListener(ILoginListener listener) {
		mListener = listener;
		return mListener == null ? false : true;
	}

	@Override
	public boolean removeLoginListener(ILoginListener listener) {
		if (null == listener)
			return false;
		mListener = null;
		return true;
	}

	@Override
	public void Login(Context context, String username, String password) {
		// 向平台发送登录请求
		StringEntity stringEntity = null;
		mobile = username;
		try {
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			Command command = new Command();
			command.addArgs("mobile", username)
					.addArgs("pwd", password)
					.addAction(Action.ACTION_LOGIN)
					.addArgs("deviceType", "a")
					.addArgs("deviceId", "1234567890987654"/*tm.getDeviceId()*/);
			stringEntity = new StringEntity(Batch.build().addCommand(command).toJson(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		HttpUtil http = new HttpUtil();
		http.req(context, stringEntity, false,new MyResponse() {
			
			@Override
			public void responseSucess(Object obj) {
				// TODO Auto-generated method stub
				LoginResponse resp = JsonUtil.toObject(obj, LoginResponse.class);
				DbManager dm = new DbManager(mContext);
				dm.updateConfig(mobile,resp);
				// 通知界面
				if (null != mListener)
					mListener.onSuccess(resp);
			}

			@Override
			public void responseFailure(String msg) {
				// TODO Auto-generated method stub
				if (null != mListener)
					mListener.onFailure(0, msg);
			}
		});
	}
	
}
